package org.karelun.whiteboard.ui.local.editor;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPersistableElement;
import org.karelun.whiteboard.Sheet;
import org.karelun.whiteboard.WhiteboardFactory;

/**
 * @Author: KarelunHuang
 * @Date: Jan 23, 2013
 **/
public class LocalEditorInput implements IEditorInput{
	
	private URI uri;
	
	public LocalEditorInput(){
		String dir = System.getProperty("user.home");
		makesureURIExists(dir+File.separator+"a.xml");
		
	}
	
	private void makesureURIExists(String path) {
		ResourceSet resourceSet = new ResourceSetImpl();
		uri= URI.createFileURI(path);
		Resource resource = resourceSet.getResource(uri, false);
		if(resource==null){
			resource=resourceSet.createResource(uri);
			saveResource(resource);
		}
		EList<EObject> contents = resource.getContents();
		if(contents.isEmpty()){
			Sheet sheet = WhiteboardFactory.eINSTANCE.createSheet();
			contents.add(sheet);
			saveResource(resource);
		}
	}
	
	private void saveResource(Resource resource){
		Map<Object, Object> options = new HashMap<Object, Object>();
		options.put(XMLResource.OPTION_ENCODING, "UTF-8");
		try {
			resource.save(options);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Object getAdapter(Class adapter) {
		if(adapter==URI.class){
			return uri;
		}
		return null;
	}

	@Override
	public boolean exists() {
		return true;
	}

	@Override
	public ImageDescriptor getImageDescriptor() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getName() {
		return "";
	}

	@Override
	public IPersistableElement getPersistable() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getToolTipText() {
		// TODO Auto-generated method stub
		return null;
	}

}
